//
//  MBDGroupDetailViewModel.swift
//  MasterBoy
//
//  Created by kyson on 2023/4/27.
//

import Foundation
import SwiftyJSON
import YYText
import Alamofire
import JLRoutes

typealias KAvatarClickedBlock = (_ cellModel:MBDGroupCommentsCellModel) ->()
typealias KReplyButtonClickedBlock = (_ cellModel:MBDGroupCommentsCellModel) ->()
typealias KPraiseButtonClickedBlock = (_ cellModel:MBDGroupCommentsCellModel) ->()
typealias KReplyPraiseButtonClickedBlock = (_ cellModel:MBDGroupCommentsReplyCellModel) ->()
typealias KGroupCommentsReplyAvatarClickedBlock = (_ cellModel:MBDGroupCommentsReplyCellModel) ->()
typealias KGroupCommentsReplyReplyButtonClickedBlock = (_ cellModel:MBDGroupCommentsReplyCellModel) ->()
typealias KGroupPraiseCompletionBlock = (_ info:Any) ->()


class MBDGroupDetailCommonCellModel : MBDCommonCellModel {
    var groupDetail : MBDGroupDetailModel!
}



class MBDGroupDetailViewModel: NSObject {
    var cellModels : Array<Any>?
    var groupDetail : MBDGroupDetailModel?
    var currentCommentId : String?
    var currentCommentUserId : String?
    //针对评论的回复
    var replyButtonClicedBlock : KReplyButtonClickedBlock?
    var praiseCompleteBlock : KGroupPraiseCompletionBlock?
    //针对回复的回复
    var groupCommentReplyButtonClicedBlock : KGroupCommentsReplyReplyButtonClickedBlock?
    
    override init() {
        super.init()
    }
    
    convenience init(groupDetail : MBDGroupDetailModel) {
        self.init()
        self.groupDetail = groupDetail
                
        self.cellModels = self.generateCellModels(groupDetail: groupDetail)
    }
    
    func generateCellModels(groupDetail : MBDGroupDetailModel!) -> Array<Any>{
       
        var cellModels = Array<Any>()
        
        let logoCellModel = MBDGroupLogoCellModel()
        logoCellModel.groupDetail =  groupDetail
        cellModels.append(logoCellModel)
        
        let gNameCellModel = MBDGroupNameCellModel()
        gNameCellModel.groupDetail =  groupDetail
        cellModels.append(gNameCellModel)
        
        let gPosterCellModel = MBDGroupPosterCellModel()
        gPosterCellModel.groupDetail =  groupDetail
        cellModels.append(gPosterCellModel)
        
        let gDescCellModel = MBDGroupDescCellModel()
        gDescCellModel.groupDetail =  groupDetail
        cellModels.append(gDescCellModel)
        
        //其中的任何一个不为空即可
        let gcU = groupDetail.groupCodeUrl
        let gcP = groupDetail.praisedQrUrl
        
        if (false == gcU?.isBlank || false == gcP?.isBlank) {
            
            let groupQRCodeTitleModel = MBDGroupQRCodeTitleCellModel()
            groupQRCodeTitleModel.groupDetail =  groupDetail
            cellModels.append(groupQRCodeTitleModel)
            
            let groupQRCodeModel = MBDGroupQRCodeCellModel()
            groupQRCodeModel.groupDetail =  groupDetail
            cellModels.append(groupQRCodeModel)
        }
        
        
        if let cm = groupDetail.groupComments {
            //个数大于 0 才展示
            if cm.count > 0 {
                let gCommentsTitleCellModel = MBDGroupCommentsTitleCellModel()
                gCommentsTitleCellModel.groupDetail =  groupDetail
                cellModels.append(gCommentsTitleCellModel)
            }

            //遍历第一层
            for item in cm {

                let gCommentsCellModel = MBDGroupCommentsCellModel()
                gCommentsCellModel.avatarClicedBlock = { cellModel in
                    let params : Dictionary = ["avatarURL":cellModel.posterAvatar,"realName":cellModel.posterRealName,"userId":cellModel.posterUserId]
                    JLRoutes.routeURL(URL(string: "userInfo"),withParameters: params as [String : Any])
                }
                
                gCommentsCellModel.replyButtonClicedBlock = { cellModel in
                    
                    if let replyButtonClicedBlock = self.replyButtonClicedBlock {
                        replyButtonClicedBlock(cellModel)
                    }
                }
                
                gCommentsCellModel.praiseButtonClicedBlock = { cellModel in
                    
                    self.doCommentPraiseRequest(groupId: cellModel.comments.groupId,groupCommentId : cellModel.comments.groupCommentId) { success, error in
                        
                        if(nil != self.praiseCompleteBlock) {
                            self.praiseCompleteBlock!(true)
                        }
                    }
                    
                }

                gCommentsCellModel.comments =  item
                cellModels.append(gCommentsCellModel)
                
                //遍历第二层
                if let replys = item.groupCommentReplyList {
                    for replyItem in replys {
                        
                        let gReplyCellModel = MBDGroupCommentsReplyCellModel()
                        gReplyCellModel.avatarClicedBlock = { rItem in
                            let params : Dictionary = ["avatarURL":rItem.posterAvatar,"realName":rItem.posterRealName,"userId":rItem.posterUserId]
                            JLRoutes.routeURL(URL(string: "userInfo"),withParameters: params as [String : Any])
                        }
                        
                        gReplyCellModel.replyButtonClicedBlock = { rItem in
                            
                            if let replyButtonClicedBlock = self.groupCommentReplyButtonClicedBlock {
                                replyButtonClicedBlock(rItem)
                            }
                        }
                        
                        gReplyCellModel.replyPraiseButtonClicedBlock = {[weak self] rItem in
                            
                            self?.doCommentReplyPraiseRequest(groupId: rItem.reply.groupId,groupCommentId :  rItem.reply.groupCommentId,groupCommentReplyId: rItem.reply.groupCommentReplyId) {[weak self] success, error in
                                
                                if(nil != self?.praiseCompleteBlock) {
                                    self?.praiseCompleteBlock!(true)
                                }
                                
                            }
                        }
                        
                        gReplyCellModel.reply = replyItem
                        cellModels.append(gReplyCellModel)

                    }
                }
                

            }
        }
        
        let unlock = (groupDetail.isUnlock as NSString).boolValue
        if true == unlock {
            let gContactsCellModel = MBDGroupContactsCellModel()
            gContactsCellModel.groupDetail =  groupDetail
            cellModels.append(gContactsCellModel)
        }
        
        return cellModels
    }
    
    
    func doDetailRequest(groupId : String, completion : @escaping (_ error : NSError?, _ result : MBDGroupDetailModel?)->()) {
        //请求
        MBDHttpClient.shared.doGetRequest("/group/getInfo",parameters: ["groupId":String(groupId) ]).httpClientResponse { error, response in
            
            if nil != error {
                completion(error,nil)
            } else {
                if let data = response?.responseObject  {
                    let detail = MBDGroupDetailModel(JSON(rawValue: data) ?? JSON(NSObject()))
                    
                    self.doCommentsListRequest(groupId: groupId) { error, result, totalPage in
                        detail.groupComments = result
                        completion(nil,detail)
                    }
                    
                } else {
                    let er = NSError(domain: "ServerErrorDomain", code: 400002,userInfo: [NSLocalizedDescriptionKey:"服务器貌似出了点问题"])
                    completion(er,nil)
                }
            }
        }        

    }
    
    func doCommentsListRequest(groupId : String, completion : @escaping (_ error : NSError?,_ result : Array<MBDGroupCommentsModel>?,_ totalPage : Int)->()) {
        //请求
        MBDHttpClient.shared.doGetRequest("/groupComment/listPage",parameters: ["groupId":String(groupId) ]).httpClientResponse { error, response in
            
            if nil != error {
                completion(error,nil,0)
            } else {
                
                let totalPage = response?.rawDict?["totalPage"] as! Int
                
                if let data = response?.responseObject  {
                    
                    if data is Array<Any> {
                        let rows = data as! Array<Any>
                        var multiRows = Array<MBDGroupCommentsModel>()
                        for row in rows {
                            let item = MBDGroupCommentsModel(JSON(rawValue: row) ?? JSON(NSObject()))
                            multiRows.append(item)
                        }
                        completion(nil,multiRows,totalPage)
                    } else {
                        let er = NSError(domain: "ServerErrorDomain", code: 400002,userInfo: [NSLocalizedDescriptionKey:"服务器貌似出了点问题"])
                        completion(er,nil,0)
                    }
                    
                }
            }
        }

    }
    
    func doPostCommentsRequest(groupId : String,commentDetail : String, completion : @escaping (_ result : MBDGroupDetailModel?,_ err : NSError? )->()) {
        //请求
        let para = ["groupId":String(groupId),"comment" : commentDetail ]
        MBDHttpClient.shared.doPostRequest("/groupComment/save",parameters:para).httpClientResponse { error, response in
            if nil != error {
                completion(nil,error)
            } else {
                self.doDetailRequest(groupId: groupId,completion: { error,result in
                    
                    completion(result,error)
                    
                })
            }
        }
    }
    
    func doPostCommentReplyRequest(groupId : String,commentId : String,userId:String? = nil,commentDetail : String, completion : @escaping (_ result : MBDGroupDetailModel?,_ err : NSError? )->()) {
        //请求
        var para = ["groupId":String(groupId),"groupCommentId":String(commentId),"comment" : commentDetail ]
        
        if userId != nil {
            para["userId"] = userId
        }
        
        MBDHttpClient.shared.doPostRequest("/groupCommentReply/save",parameters:para).httpClientResponse { error, response in
            if nil != error {
                completion(nil,error)
            } else {
                self.doDetailRequest(groupId: groupId,completion: { error,result in
                    
                    completion(result,error)
                    
                })
            }
        }
    }
    
    func doGroupPraiseUpdateRequest(groupId : String, groupCommentId : String = "", completion : @escaping (_ result : Bool?,_ err : NSError? )->()) {
        //请求
        var para = [String:String]()
        para["groupId"] = String(groupId)
        
        MBDHttpClient.shared.doPostRequest("/groupLike/saveOrCancel",parameters:para).httpClientResponse { error, response in
            if nil != error {
                completion(nil,error)
            } else {
                completion(true,nil)
            }
        }
    }
    
    
    func doCommentPraiseRequest(groupId : String, groupCommentId : String = "", completion : @escaping (_ result : Bool?,_ err : NSError? )->()) {
        //请求
        var para = [String:String]()
        para["groupId"] = String(groupId)
        
        if groupCommentId.isBlank == false {
            para["groupCommentId"] = String(groupCommentId)
        }
        
        MBDHttpClient.shared.doPostRequest("/groupLike/groupComment/saveOrCancel",parameters:para).httpClientResponse { error, response in
            if nil != error {
                completion(nil,error)
            } else {
                completion(true,nil)

            }
        }
    }
    
    func doCommentReplyPraiseRequest(groupId : String, groupCommentId : String = "",groupCommentReplyId : String = "", completion : @escaping (_ result : Bool?,_ err : NSError? )->()) {
        //请求
        var para = [String:String]()
        para["groupId"] = String(groupId)
        
        if groupCommentReplyId.isBlank == false {
            para["groupCommentReplyId"] = String(groupCommentReplyId)
        }
        
        if groupCommentId.isBlank == false {
            para["groupCommentId"] = String(groupCommentId)
        }
        
        MBDHttpClient.shared.doPostRequest("/groupLike/groupCommentReply/saveOrCancel",parameters:para).httpClientResponse { error, response in
            if nil != error {
                completion(nil,error)
            } else {
                completion(true,nil)

            }
        }
    }
    
    
    func doUnLockRequest(groupId : String, completion : @escaping (_ result : MBDGroupDetailModel?,_ err : NSError? )->()) {
        //请求
        let para = ["groupId":String(groupId) ]
        MBDHttpClient.shared.doPostRequest("/userGroupUnlock/save",parameters:para).httpClientResponse { error, response in
            if nil != error {
                completion(nil,error)
            } else {
                self.doDetailRequest(groupId: groupId,completion: { error,result in
                    
                    completion(result,error)
                    
                })
            }
        }
    }
    
    
    
}
